package controller

import (
	"errors"
	"fmt"
	"image"
	"image/png"
	"os"
	"path/filepath"
	"runtime"
	"time"

	"github.com/kbinani/screenshot"
)

type screenApp struct {
	Base
}

func NewScreenApp() *screenApp {
	return &screenApp{}
}

// TakeScreenshot 截取屏幕并保存为PNG文件
func (a *screenApp) TakeScreenshot() (string, error) {
	// 获取屏幕数量
	n := screenshot.NumActiveDisplays()
	if n <= 0 {
		return "", errors.New("没有找到可用的显示器")
	}

	// 获取所有显示器的边界
	var allBounds image.Rectangle
	for i := 0; i < n; i++ {
		bounds := screenshot.GetDisplayBounds(i)
		allBounds = allBounds.Union(bounds)
	}

	// 截取整个屏幕区域
	img, err := screenshot.Capture(allBounds.Min.X, allBounds.Min.Y, allBounds.Dx(), allBounds.Dy())
	if err != nil {
		return "", fmt.Errorf("截屏失败: %v", err)
	}

	// 创建保存目录
	dir, err := getScreenshotDir()
	if err != nil {
		return "", fmt.Errorf("创建目录失败: %v", err)
	}

	// 生成文件名
	timestamp := time.Now().Format("2006-01-02_15-04-05")
	filename := filepath.Join(dir, "screenshot_"+timestamp+".png")

	// 保存文件
	file, err := os.Create(filename)
	if err != nil {
		return "", fmt.Errorf("创建文件失败: %v", err)
	}
	defer file.Close()

	err = png.Encode(file, img)
	if err != nil {
		return "", fmt.Errorf("保存PNG失败: %v", err)
	}

	return filename, nil
}

// getScreenshotDir 获取截图保存目录
func getScreenshotDir() (string, error) {
	var dir string
	switch runtime.GOOS {
	case "windows":
		dir = filepath.Join(os.Getenv("USERPROFILE"), "Pictures", "Screenshots")
	case "darwin":
		dir = filepath.Join(os.Getenv("HOME"), "Pictures", "Screenshots")
	default: // Linux and others
		dir = filepath.Join(os.Getenv("HOME"), "Pictures", "Screenshots")
	}

	if err := os.MkdirAll(dir, 0755); err != nil {
		return "", err
	}

	return dir, nil
}
